package dormouse.fx.renderers;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javafx.scene.image.Image;

import javax.annotation.PostConstruct;

import org.apache.commons.vfs2.FileObject;

import dormouse.vfs.ui.renderers.IFileIconFactory;

public class FileIconFactory implements IFileIconFactory<Image> {
	
	/** A map of the file extensions, and the icons used for those extensions. */
	private Map<String, String> iconMap = new HashMap<String, String>();
	
	private String defaultDirectory = null;
	
	/**
	 * Constructor.
	 */
	public FileIconFactory(){
		
	}
	
	@PostConstruct
	public void setIconMap(Map<String, String> iconMap){
		if (!iconMap.containsKey(DEFAULT)){
			throw new IllegalArgumentException("The icon map must contain a default file icon mapping");
		}
		this.iconMap = iconMap;
	}
	
	@PostConstruct
	public void setDefaultDirectory(String dir){
		this.defaultDirectory = dir;
	}

	@Override
	public Image getFileIcon(FileObject file) {
		String ext = file.getName().getExtension();
		String iconPath = iconMap.get(ext);
		if (iconPath == null){
			iconPath = iconMap.get(DEFAULT);
		}
		
		if (defaultDirectory != null){
			iconPath = defaultDirectory + iconPath;
		}
		
		InputStream is =  FileIconFactory.class.getResourceAsStream(iconPath);
		if (is == null){
			throw new IllegalStateException("Unable to get icon for: " + iconPath);
		}
		
		
		return new Image(is);
	}

	@Override
	public String[] getExtensions() {
		
		Set<String> extSet = iconMap.keySet();
		List<String> extList = new ArrayList<>(extSet);
		
		String[] extArray = new String[extList.size()];
		extArray = extList.toArray(extArray);
		
		return extArray;
	}

}
